﻿using Acorisoft.FutureGL.MigaDB.Models;
using LiteDB;

namespace KinonekoSoftware.Studio.Utils.Transformers
{
    public sealed class RepositoryTransformer : Transformer
    {
        private const string OldCollectionName = "props";

        public override void Migrate(TransformContext context)
        {
            var sourcesDirectory  = Path.Combine(context.OldRepoDir, "Sources");
            var musicsDirectory   = Path.Combine(context.OldRepoDir, "Musics");
            var imageDirectory    = Path.Combine(context.OldRepoDir, "Image");
            var propertyFileName  = Path.Combine(context.OldRepoDir, "index.mgidx");
            var oldVersion        = CheckDirectory(Path.Combine(context.NewRepoDir, "OldVersion"));
            var oldVersionsources = CheckDirectory(Path.Combine(oldVersion, "Sources"));
            var oldVersionmusics  = CheckDirectory(Path.Combine(oldVersion, "Musics"));
            var oldVersionImage   = CheckDirectory(Path.Combine(oldVersion, "Image"));

            
            if (context.OldRepo.CollectionExists(OldCollectionName))
            {
                var oldCol   = context.OldRepo.GetCollection<BsonDocument>(OldCollectionName);
                var document = oldCol.FindById("Acorisoft.Miga.Doc.Core.RepositoryProperty");

                if (document is not null)
                {
                    context.Repository.Author      = document["Author"].AsString;
                    context.Repository.Name        = document["Name"].AsString;
                    context.Repository.ForeignName = document["EnglishName"].AsString;
                    context.Repository.Intro       = document["Summary"].AsString;
                    context.Repository.UpdateProperty();
                }
            }

            if (File.Exists(propertyFileName))
            {
                var property = JSON.File<DatabaseProperty>(propertyFileName);
                context.Repository.Author      = property.Author;
                context.Repository.Name        = property.Name;
                context.Repository.ForeignName = property.ForeignName;
                context.Repository.Intro       = property.Intro;
                context.Repository.UpdateProperty();
            }
            
            
            if(Directory.Exists(sourcesDirectory)) Directory.Move(sourcesDirectory, oldVersionsources);
            if(Directory.Exists(musicsDirectory)) Directory.Move(musicsDirectory, oldVersionmusics);
            if(Directory.Exists(imageDirectory)) Directory.Move(imageDirectory, oldVersionImage);
        }
    }
}